package com.mogist.hqc.module.product.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.ldf.calendar.Utils
import com.ldf.calendar.component.CalendarAttr
import com.ldf.calendar.component.CalendarViewAdapter
import com.ldf.calendar.interf.OnSelectDateListener
import com.ldf.calendar.model.CalendarDate
import com.ldf.calendar.view.MonthPager
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.DayPriceVo
import com.mogist.hqc.entitys.response.ProductDetailVo
import com.mogist.hqc.entitys.response.ProductOrderVo
import com.mogist.hqc.entitys.response.UploadVo
import com.mogist.hqc.module.product.adapter.ProductOrderItemAdapter
import com.mogist.hqc.module.product.adapter.ProductOrderSureAdapter
import com.mogist.hqc.module.product.contract.ProductChooseContract
import com.mogist.hqc.module.product.presenter.ProductChoosePresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.CustomDayView
import kotlinx.android.synthetic.main.activity_product_choose.*
import kotlinx.android.synthetic.main.include_title.*
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.util.DimenTool
import talex.zsw.basecore.util.RegTool
import talex.zsw.basecore.util.TimeTool
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.other.flowlayout.FlowLayout
import talex.zsw.basecore.view.other.flowlayout.TagAdapter
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*
import kotlin.collections.HashMap

/**
 * 作用：选择类型/日期/人数
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class ProductChooseActivity : BaseMVPActivity<ProductChooseContract.Presenter>(), ProductChooseContract.View
{
    private var detail: ProductDetailVo? = null
    override fun initArgs(intent: Intent)
    {
        intent.getSerializableExtra("detail")
                ?.let {
                    detail = it as ProductDetailVo
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_product_choose)
        mPresenter = ProductChoosePresenter(this)
    }

    override fun initData()
    {
        initFlowLayout()
        initMonth()
        initRecyclerView()
        setDateInfo(0)
        mTitleBar.setTitle("选择类型/日期/人数")
    }

    @Optional
    @OnClick(R.id.mTvPrice, R.id.mTvSure, R.id.mTvMask, R.id.mTvPre, R.id.mTvNext)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvPrice ->
                {
                    if (mLLOrder.visibility == View.GONE)
                    {
                        if (hasDayPriceVo && sumCount > 0)
                        {
                            mLLOrder.visibility = View.VISIBLE
                            showSureOrderList()
                        }
                        else
                        {
                            RxToast.error("请选择您要购买的票型")
                        }
                    }
                    else
                    {
                        mLLOrder.visibility = View.GONE
                    }
                }
                R.id.mTvMask  ->
                {
                    mLLOrder.visibility = View.GONE
                }
                R.id.mTvSure  ->
                {
                    if (mLLOrder.visibility == View.GONE)
                    {
                        mLLOrder.visibility = View.VISIBLE
                        showSureOrderList()
                    }
                    else if (sumB.toDouble()<=0)
                    {
                        RxToast.error("总金额为0.00无法下单")
                    }
                    else
                    { // 填写联系人信息
                        val data = UploadVo()
                        data.pdtId = detail!!.id
                        data.pdtName = detail!!.pdtName
                        data.proId = selectItem?.id
                        data.proName = selectItem?.pdtName
                        data.price =
                                sumB.setScale(2, RoundingMode.HALF_UP)
                                        .toPlainString()
                        data.basePlace = detail!!.basePlace
                        data.travelDate = selectDateStr
                        data.adultNum = adapter.data[0].count
                        data.childNum = adapter.data[1].count
                        data.list = sureAdapter.data as ArrayList<ProductOrderVo>?
                        val intent =
                                Intent(this@ProductChooseActivity,
                                       ProductUploadActivity::class.java)
                        intent.putExtra("data", data)
                        start(intent)
                    }
                }
                R.id.mTvPre   ->
                {
                    setDateInfo(-1)
                }
                R.id.mTvNext  ->
                {
                    setDateInfo(1)
                }
            }
        }
    }

    private fun showSureOrderList()
    {
        val list: ArrayList<ProductOrderVo> = arrayListOf()
        for (vo in adapter.data)
        {
            if (vo.count > 0 && RegTool.isNotEmpty(vo.price))
            {
                list.add(vo)
            }
        }
        sureAdapter.replaceData(list)
    }

    // --------------- 类型选择 ---------------
    private var values = arrayListOf<String>()
    private var selectItem: ProductDetailVo.ProductProListEntity? = null
    private var selectPos = -1
    private fun initFlowLayout()
    {
        values = arrayListOf()
        detail!!.productProList.forEach {
            values.add(it.pdtName)
        }
        val flowAdapter = object : TagAdapter<String>(values)
        {
            override fun getView(parent: FlowLayout, position: Int, s: String): View
            {
                val tv =
                        layoutInflater.inflate(R.layout.view_flow_text,
                                               mFlowLayout,
                                               false) as TextView
                tv.text = s
                return tv
            }
        }
        // 设置适配器
        mFlowLayout.setAdapter(flowAdapter)
        // Tag选中的回调事件
        mFlowLayout.setOnSelectListener {
            for (i in it)
            {
                selectItem = detail!!.productProList[i]
                if (selectPos != i)
                {
                    selectPos = i
                    setDateInfo(0)
                }
            }
        }

        mFlowLayout.setMaxSelectCount(1)
        flowAdapter.setSelectedList(0)
        selectPos = 0
        selectItem = detail!!.productProList[0]
    }

    // --------------- 日历日价格 ---------------
    private var calendarAdapter: CalendarViewAdapter? = null

    private fun initMonth()
    {
        mMonthPager.viewHeight = DimenTool.dp2px(270f)
        mMonthPager.setScrollable(false)
        val customDayView = CustomDayView(this@ProductChooseActivity, R.layout.custom_day)
        calendarAdapter =
                CalendarViewAdapter(this@ProductChooseActivity,
                                    onSelectDateListener,
                                    CalendarAttr.CalendarType.MONTH,
                                    CalendarAttr.WeekArrayType.Monday,
                                    customDayView)
        mMonthPager.adapter = calendarAdapter
        mMonthPager.currentItem = MonthPager.CURRENT_DAY_INDEX
        mMonthPager.setPageTransformer(false, ViewPager.PageTransformer { page, position ->
            var position = position
            position =
                    Math.sqrt((1 - Math.abs(position)).toDouble())
                            .toFloat()
            page.alpha = position
        })
    }

    var selectDateStr = TimeTool.getDateString(Date(), "yyyy-MM-dd")
    private val onSelectDateListener = object : OnSelectDateListener
    {
        override fun onSelectDate(date: CalendarDate)
        {
            selectDateStr = TimeTool.changeFormat(date.toString(), "yyyy-M-d", "yyyy-MM-dd")
            if (Utils.loadMarkData().containsKey(selectDateStr))
            {
                priceList?.forEachIndexed { index, dayPriceVo ->
                    if (priceList!![index].saleDate.startsWith(selectDateStr))
                    {
                        for (i in priceList!!.indices)
                        {
                            if (priceList!![i].saleDate.startsWith(selectDateStr))
                            {
                                bindItem(priceList!![i])
                                break
                            }
                        }
                    }
                }
            }
            else
            {
                setSelectNull()
            }
        }

        override fun onSelectOtherMonth(offset: Int)
        {
            if (offset<0 && mTvPre.isEnabled)
            {
                setDateInfo(-1)
            }
            else if (offset>0 && mTvNext.isEnabled)
            {
                setDateInfo(1)
            }
        }
    }

    private fun setSelectNull()
    {
        hasDayPriceVo = false
        mTvSure.isEnabled = false
        mTvPrice.text = "￥0.00"
        sumCount = 0
        mLLCount.visibility = View.GONE
    }

    private var offset = 0
    private var currentPos = 1000
    private fun setDateInfo(offset: Int)
    {
        this.offset = offset
        val currentPos = currentPos + offset
        mTvPre.isEnabled = true
        mTvNext.isEnabled = true
        if (currentPos == 1006)
        {
            mTvNext.isEnabled = false
        }
        var date = Date()
        if (currentPos == 1000)
        {
            mTvPre.isEnabled = false
            mTvMonth.text = TimeTool.getDateString(date, "yyyy-MM")
        }
        else
        {
            val c = Calendar.getInstance()
            c.time = date
            c.add(Calendar.MONTH, currentPos - 1000)
            date = c.time
        }
        mTvMonth.text = TimeTool.getDateString(date, "yyyy-MM")
        val body = BaseModel()
        body.id = detail!!.id
        body.proId = selectItem!!.id
        if (currentPos == 1000)
        {
            body.beginDate = TimeTool.getDateString(Date(), TimeTool.STR_FOMATER_DATA)
            body.endDate =
                    TimeTool.getDateString(TimeTool.getMonthEnd(date), TimeTool.STR_FOMATER_DATA)
        }
        else
        {
            body.beginDate =
                    TimeTool.getDateString(TimeTool.getMonthStart(date), TimeTool.STR_FOMATER_DATA)
            body.endDate =
                    TimeTool.getDateString(TimeTool.getMonthEnd(date), TimeTool.STR_FOMATER_DATA)
        }
        mPresenter.getData(HttpDto(Constant.PRODUCT_DAILY_PRICE,
                                   body).setType(HttpDto.GET).setErrorTitle("获取产品日价格失败"))
    }

    var priceList: ArrayList<DayPriceVo>? = null
    override fun bindPrice(list: ArrayList<DayPriceVo>?)
    {
        priceList = list
        mMonthPager.currentItem = mMonthPager.currentPosition + offset
        currentPos = mMonthPager.currentPosition
        if (list != null && list.isNotEmpty())
        {
            var flag = false
            val map: HashMap<String, String> = HashMap()
            for (vo in list)
            {
                if (vo.saleDate.startsWith(selectDateStr))
                {
                    flag = true
                    bindItem(vo)
                }
                map[Util.getTimeStr(vo.saleDate)] = vo.adultPrice
            }
            hasDayPriceVo = flag
            if (!flag)
            {
                setSelectNull()
            }
            calendarAdapter?.setMarkData(map)
        }
        mMonthPager.currentItem = mMonthPager.currentPosition + 1
        mMonthPager.currentItem = mMonthPager.currentPosition - 1
    }

    // --------------- 绑定票型价格 ---------------
    private var hasDayPriceVo = false

    private fun bindItem(data: DayPriceVo)
    {
        hasDayPriceVo = true
        mLLCount.visibility = View.VISIBLE
        if (RegTool.isNotEmpty(data.adultPrice))
        {
            orderList[0].price = data.adultPrice
        }
        else
        {
            orderList[0].price = ""
        }
        if (RegTool.isNotEmpty(data.childPrice))
        {
            orderList[1].price = data.childPrice
        }
        else
        {
            orderList[1].price = ""
        }
        adapter.notifyDataSetChanged()
        showPrice()
    }

    private val orderList: ArrayList<ProductOrderVo> = arrayListOf()
    private val adapter = ProductOrderItemAdapter()
    private val sureAdapter = ProductOrderSureAdapter()
    private fun initRecyclerView()
    {
        adapter.setOnItemChildClickListener { a, view, position ->
            val item = adapter.getItem(position)!!

            when (view.id)
            {
                R.id.iIvReduce  ->
                {
                    adapter.data[position].count = item.count - 1
                    adapter.notifyDataSetChanged()
                    showPrice()
                }
                R.id.iIvAdd     ->
                {
                    adapter.data[position].count = item.count + 1
                    adapter.notifyDataSetChanged()
                    showPrice()
                }
                R.id.iLLContent ->
                {
                }
            }
        }
        mRecyclerView.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                              R.color.transparent))
        mRecyclerView.layoutManager = LinearLayoutManager(this@ProductChooseActivity)
        mRecyclerView.adapter = adapter
        orderList.add(ProductOrderVo("成人", ""))
        orderList.add(ProductOrderVo("儿童", ""))
        adapter.replaceData(orderList)

        mRvOrder.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                         R.color.transparent))
        mRvOrder.layoutManager = LinearLayoutManager(this@ProductChooseActivity)
        mRvOrder.adapter = sureAdapter
    }

    private var sumB = BigDecimal(0)
    private var sumCount = 0
    @SuppressLint("SetTextI18n")
    private fun showPrice()
    {
        sumB = BigDecimal(0)
        sumCount = 0
        for (vo in adapter.data)
        {
            if (RegTool.isNotEmpty(vo.price) && vo.count > 0)
            {
                val priceB = BigDecimal(vo.price)
                sumCount += vo.count
                sumB = sumB.add(priceB.multiply(BigDecimal(vo.count)))
            }
        }
        mTvPrice.text = "￥${sumB.setScale(2, RoundingMode.HALF_UP).toPlainString()}"
        mTvSure.isEnabled = sumCount > 0
    }

    // --------------- EventBus ---------------
    @Subscribe
    fun onEvent(event: String)
    {
        if (Constant.EVENT_UPLOAD_SUCCESS == event)
        {
            finish()
        }
        else if (Constant.EVENT_PAY_SUCCESS == event)
        {
            finish()
        }
    }

}